package com.jzo2o.trade.xxjob;

import cn.hutool.json.JSONUtil;
import com.jzo2o.api.trade.enums.PayChannelEnum;
import com.jzo2o.trade.config.WxPayConfig;
import com.jzo2o.trade.config.WxPayProperties;
import com.jzo2o.trade.model.domain.Trading;
import com.jzo2o.trade.service.IPaySuccessService;
import com.jzo2o.trade.service.ITradingService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * \* User: chy
 * \* Date: 2025/10/8  19:56
 * \* Description:
 * \
 */
@Component
@Slf4j
public class PayStatusJob {
    @Resource
    private ITradingService tradingService;
    @Resource
    private Config config;
    @Resource
    private WxPayProperties wxPayProperties;
    @Resource
    private IPaySuccessService paySuccessService;

    @XxlJob("payStatusJob")
    public void payStatusJob() {
        log.info("支付状态任务开始执行");
        //TODO:查询所有5分钟前付款中的支付订单
        List<Trading> tradingList = tradingService.selectPayStatus();
        if (CollectionUtils.isEmpty(tradingList)) {
            log.info("没有待更改的支付订单");
            return;
        }
        //遍历所有待更改的支付订单,去调用微信接口查询支付状态
        for (Trading trading : tradingList) {
            //通过交易单号查询第三方支付订单
            //这里是微信的
            if (trading.getTradingChannel().equals(PayChannelEnum.WECHAT_PAY.getValue())) {
                //交易单号
                String tradingOrderNo = trading.getTradingOrderNo();
                //创建查询请求
                Transaction result = queryResult(tradingOrderNo);
                if (result.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
                    //更新支付订单状态
                    //, result.getTransactionId()
                    paySuccessService.updateTradingState(trading.getTradingOrderNo());
                }
            }
        }
    }
    /**
     * 查询微信支付订单
     *
     * @param tradingOrderNo
     * @return
     */
    public Transaction queryResult(String tradingOrderNo) {
        // 构造查询请求参数
        QueryOrderByOutTradeNoRequest orderByOutTradeNoRequest = new QueryOrderByOutTradeNoRequest();
        // 商户号
        orderByOutTradeNoRequest.setMchid(wxPayProperties.getMerchantId());
        // 商户支付订单号
        orderByOutTradeNoRequest.setOutTradeNo(tradingOrderNo);

        // 构建Native支付服务实例
        NativePayService service = new NativePayService.Builder().config(config).build();

        try {
            // 调用微信查询订单接口
            Transaction result = service.queryOrderByOutTradeNo(orderByOutTradeNoRequest);
            // 将查询结果转换为JSON字符串返回
            return result;

        } catch (ServiceException e) {
            // API返回失败情况处理，例如订单不存在
            log.error("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
            log.error("response body=[%s]\n", e.getResponseBody());

            // 返回错误信息  //todo:这里待完善
            return null;
        }
    }
}
